package com.example.test.conbase.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.trello.rxlifecycle2.components.support.RxFragment;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Fragment 基类
 * @param <V> 泛型view
 * @param <P> 泛型Presenter
 *     父类->基类->动态指定类型->泛型设计（通过泛型指定动态类型->由子类指定，父类只需要规定范围即可）
 */
public abstract class BaseFragment<V extends BaseView, P extends BasePresenter<V>>
        extends RxFragment  {
    /**
     * 引用P层
     */
    private P presenter;
    /**
     * 引用V层
     */
    private V view;
    public Context mContext;
    private Unbinder unbinder;

    /**
     * 获取presenter对象
     * @return presenter对象
     */
    public P getPresenter() {
        return presenter;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        unbinder = ButterKnife.bind(this, view);
        mContext = getActivity();
        if (presenter == null) {
            presenter = createPresenter();
        }
        if (this.view == null) {
            this.view = createView();
        }
        if (presenter != null && view != null) {
            presenter.attachView(this.view);
        }
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    /**
     * 获取布局文件
     *
     * @return 布局文件id
     */
    public abstract int getLayoutId();

    /**
     * 初始化Presenter
     * @return  Presenter对象
     */
    public abstract P createPresenter();

    /**
     * 初始化View对象
     * @return View对象
     */
    public abstract V createView();

    /**
     * 初始化数据
     */
    public abstract void init();

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 释放View
        if (presenter != null) {
            presenter.detachView();
        }
        // 解除绑定
        if (unbinder != null) {
            unbinder.unbind();
        }
    }
}
